package com.adcc.ags.gms.user.controller;

import com.adcc.ags.gms.core.util.Constant;
import com.adcc.ags.gms.core.util.LogFactory;
import com.adcc.ags.gms.core.vo.ResultState;
import com.adcc.ags.gms.core.vo.ResultVO;
import com.adcc.ags.gms.user.entity.BlackList;
import com.adcc.ags.gms.user.service.BlackListService;
import com.adcc.ags.gms.user.service.GWUserService;
import com.adcc.ags.gms.user.vo.BlackListVO;
import com.adcc.ags.gms.user.vo.GWUserVO;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.List;

@Controller
@RequestMapping(value = "/blackList", produces = MediaType.APPLICATION_JSON_VALUE)
public class BlackListController {

    @Autowired
    private BlackListService blackListService;
    @Autowired
    private GWUserService gwUserService;
    @Autowired
    private LogFactory log;

    /**
     * 黑名单用户名下拉框选择
     * @return
     */
    @RequestMapping(value = "/getBGSUsers", method = RequestMethod.GET)
    public @ResponseBody List<GWUserVO> getBGSUsers() {
        List<GWUserVO> list = null;
        try {
            Optional<List<GWUserVO>> optional = gwUserService.findAllGWUser();
            list = optional.get();
        } catch (Exception ex) {
            log.error(BlackListController.class, "getBGSUsers() error", ex);
        }
        return list;
    }

    @RequestMapping(value = "/findByGWUserID", method = RequestMethod.GET)
    public @ResponseBody ResultVO findByGWUserId(@RequestParam("gwUserId")long gwUserId) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<Boolean> optional = blackListService.findByGWUserId(gwUserId);
            if (optional.isPresent()) {
                if (optional.get()) {
                    resultVO.setCode(0);
                    resultVO.setState(ResultState.FAILURE);
                    resultVO.setReason("黑名单用户名已存在");
                }
            }else{
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(BlackListController.class, "findByName() error", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody ResultVO createBlackList(BlackListVO blackListVO) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<Boolean> optional = blackListService.addBlackList(blackListVO);
            if (!optional.isPresent()) {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(BlackListController.class, "createBlackList() fail",  ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public @ResponseBody ResultVO updateBlackList(@PathVariable("id") long id, @RequestBody BlackListVO blackListVO) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<Boolean> optional = blackListService.updateBlackList(blackListVO);
            if (!optional.isPresent()) {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(BlackListController.class, "updateBlackList() fail", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public @ResponseBody ResultVO deleteBlackList(@PathVariable("id") Long id) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<Boolean> optional = blackListService.deleteBlackList(id);
            if (!optional.isPresent()) {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(BlackListController.class, "deleteBlackList() fail", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    @RequestMapping(value = "/getAllBlackListByCondition", method = RequestMethod.GET)
    public @ResponseBody ResultVO<BlackListVO> getAllBlackListByCondition(long gwUserId, int currentPage, int pageSize) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<PageInfo<BlackList>> optional = blackListService.findAllBlackListByCondition(gwUserId, currentPage, pageSize);
            if(optional.isPresent()){
                resultVO.setPageInfo(optional.get());
                if(optional.get().getList().size() > 0){
                    List<BlackListVO> list = Lists.newArrayListWithExpectedSize(100);
                    for(BlackList blackList : optional.get().getList()){
                        BlackListVO vo = new BlackListVO(blackList);
                        list.add(vo);
                    }
                    resultVO.getData().put("BlackListVO",list);
                }
            }else {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }

            return resultVO;
        } catch (Exception ex) {
            log.error(BlackListController.class, "getAllBlackListByCondition() fail", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
            return resultVO;
        }
    }

    @RequestMapping(value = "/push", method = RequestMethod.GET)
    public @ResponseBody ResultVO push() {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<Boolean> optional = blackListService.updateBlackListConf();
            if (optional.isPresent()) {
                if (optional.get()) {
                    resultVO.setCode(0);
                    resultVO.setState(ResultState.SUCCESS);
                    resultVO.setReason("推送黑名单用户配置至CGW返回成功！");
                } else {
                    resultVO.setCode(-1);
                    resultVO.setState(ResultState.FAILURE);
                    resultVO.setReason("黑名单信息列表为空");
                }
            } else {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GW_UPDATE_BLACKLIST_ERROR);
            }
        } catch (Exception ex) {
            log.error(BlackListController.class, "Push blackList fail", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    @RequestMapping(value = "/downloadBlackList", method = RequestMethod.GET)
    public void downloadBlackList(HttpServletResponse response) {
        XMLWriter xw = null;
        StringWriter sw = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            int intLength = -1;
            byte[] data = null;
            byte[] buffer = new byte[1024];
            Document document = blackListService.createBlackList();

            // 设置Http文件下载协议
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.MULTIPART_FORM_DATA.toString());
            response.setHeader("Content-Disposition","attachment;fileName=" + Constant.BLACKLIST_FILE_NAME);

            if(document != null){
                // 输出文件流
                sw = new StringWriter();
                xw = new XMLWriter(sw, OutputFormat.createPrettyPrint());
                xw.write(document);
                data = sw.getBuffer().toString().getBytes();
                is = new ByteInputStream(data,data.length);
                os = response.getOutputStream();
                while ((intLength = is.read(buffer, 0, buffer.length)) > -1){
                    os.write(buffer,0,intLength);
                    os.flush();
                }
            }
        } catch (Exception ex) {
            log.error(BlackListController.class, "downloadBlackList() error", ex);
        }finally {
            try{
                if(os != null){
                    os.close();
                }
                if(is != null){
                    is.close();
                }
                if(sw != null){
                    sw.close();
                }
                if(xw != null){
                    xw.close();
                }
            }catch (Exception ex){
                log.error(BlackListController.class, "close IO error", ex);
            }
        }
    }

}
